<?php

namespace App\Http\Middleware;

use App\Models\AdminUser;
use App\Http\Controllers\Business\ConsoleWeb\Auth\AdminAuth;
use Closure;
use Dingo\Api\Facade\Route;
use Illuminate\Support\Facades\Redis;

class AdminApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        if(!$request->get('token')) {
            echo json_encode(['status'=>'failed', 'message'=>'认证失败，重新登录']);
            exit;
        } else {
            $adminUserId = AdminAuth::getUserIdByToken($request->get('token'));
            if($adminUserId) {
                $profile = Route::currentRouteName();
                $auth = Redis::get('AdminAuth:'.$adminUserId);
                if($auth) {
                    $auth = json_decode($auth,true);
                    if(is_int(array_search($profile,$auth))) {
                        return $next($request);
                    } else {
                        echo json_encode(['status'=>'failed', 'message'=>'您没有权限访问该模块!']);
                        exit;
                    }
                } else {
                    $auth = AdminUser::where('id', $adminUserId)->pluck('auth')->first();
                    if($auth) {
                        Redis::set('AdminAuth:'.$adminUserId,$auth);
                        $auth = json_decode($auth,true);
                        if(is_int(array_search($profile,$auth))) {
                            return $next($request);
                        } else {
                            echo json_encode(['status'=>'failed', 'message'=>'您没有权限访问该模块！']);
                            exit;
                        }
                    } else {
                        echo json_encode(['status'=>'failed', 'message'=>'您没有权限访问该模块！']);
                        exit;
                    }
                }
            } else {
                echo json_encode(['status'=>'failed', 'message'=>'认证失败，重新登录']);
                exit;
            }
        }
    }
}
